package com.ruoyi.project.system.controller;

import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.project.system.domain.ReservationAll;
import com.ruoyi.project.system.service.ReservationAllService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 预约管理 Controller（类名修改 + 调用新的取消预约方法）
 */
@RestController
@RequestMapping("/reservation") // 前端请求 /dev-api/reservation/xxx 映射到此
public class ReservationAllController {

    private static final Logger logger = LoggerFactory.getLogger(ReservationAllController.class);

    @Autowired
    private ReservationAllService reservationAllService;

    /**
     * 接口1：查询当前用户预约列表
     */
    @GetMapping("/my")
    public AjaxResult getMyReservations() {
        try {
            Long userId = SecurityUtils.getUserId();
            if (userId == null || userId <= 0) {
                logger.error("查询预约列表失败：用户未登录");
                return AjaxResult.error("用户未登录，请重新登录");
            }

            List<ReservationAll> reservations = reservationAllService.getMyReservations(userId);
            logger.info("用户{}查询预约列表成功，共{}条记录", userId, reservations.size());
            return AjaxResult.success(reservations);
        } catch (Exception e) {
            logger.error("查询预约列表失败", e);
            return AjaxResult.error("查询预约失败，请重试");
        }
    }

    /**
     * 接口2：取消预约（含回退名额）
     */
    @PostMapping("/cancel/{resId}")
    public AjaxResult cancelReservation(@PathVariable String resId) {
        try {
            Long userId = SecurityUtils.getUserId();
            if (userId == null || userId <= 0) {
                logger.error("取消预约失败：用户未登录");
                return AjaxResult.error("用户未登录，请重新登录");
            }

            // 调用含回退名额的取消方法
            boolean success = reservationAllService.cancelReservationWithRestoreQuota(resId);
            if (success) {
                logger.info("用户{}取消预约{}成功，名额已回退", userId, resId);
                return AjaxResult.success("取消预约成功，名额已释放");
            } else {
                return AjaxResult.error("取消预约失败");
            }
        } catch (RuntimeException e) {
            logger.error("取消预约失败", e);
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("取消预约异常", e);
            return AjaxResult.error("取消预约失败，请重试");
        }
    }
}